document.addEventListener('DOMContentLoaded', function() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    const fileInfo = document.getElementById('fileInfo');
    const fontSizeSlider = document.getElementById('fontSize');
    const fontSizeValue = document.getElementById('fontSizeValue');
    const lineHeightSlider = document.getElementById('lineHeight');
    const lineHeightValue = document.getElementById('lineHeightValue');
    const fontColorPicker = document.getElementById('fontColor');
    const fontColorValue = document.getElementById('fontColorValue');
    const hotkeyNext = document.getElementById('hotkeyNext');
    const hotkeyPrev = document.getElementById('hotkeyPrev');
    const windowLengthSlider = document.getElementById('windowLength');
    const windowLengthValue = document.getElementById('windowLengthValue');
    const currentPageInput = document.getElementById('currentPage');
    const pageDisplay = document.getElementById('pageDisplay');
    const goToPageBtn = document.getElementById('goToPageBtn');

    // 记录总页数
    let totalPages = 0;

    // 加载保存的设置
    chrome.storage.sync.get([
        'fontSize', 
        'lineHeight', 
        'fontColor', 
        'hotkeyNext', 
        'hotkeyPrev',
        'windowLength',
        'fileName',
        'currentPosition'
    ], function(result) {
        if (result.fontSize) {
            fontSizeSlider.value = result.fontSize;
            fontSizeValue.textContent = result.fontSize + 'px';
        }
        if (result.lineHeight) {
            lineHeightSlider.value = result.lineHeight;
            lineHeightValue.textContent = result.lineHeight;
        }
        if (result.fontColor) {
            fontColorPicker.value = result.fontColor;
            fontColorValue.textContent = result.fontColor;
        }
        if (result.hotkeyNext) {
            hotkeyNext.value = result.hotkeyNext;
        }
        if (result.hotkeyPrev) {
            hotkeyPrev.value = result.hotkeyPrev;
        }
        if (result.windowLength) {
            windowLengthSlider.value = result.windowLength;
            windowLengthValue.textContent = result.windowLength;
        }
        if (result.fileName) {
            fileInfo.textContent = '已加载文件: ' + result.fileName;
            fileInfo.style.color = '#4CAF50';
            
            // 加载文件后更新页码显示
            updatePageDisplay();
        }
    });

    // 处理文件上传
    uploadArea.addEventListener('click', function() {
        fileInput.click();
    });

    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.style.backgroundColor = '#f0f0f0';
    });

    uploadArea.addEventListener('dragleave', function() {
        uploadArea.style.backgroundColor = 'transparent';
    });

    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.style.backgroundColor = 'transparent';
        
        if (e.dataTransfer.files.length > 0) {
            handleFile(e.dataTransfer.files[0]);
        }
    });

    fileInput.addEventListener('change', function() {
        if (fileInput.files.length > 0) {
            handleFile(fileInput.files[0]);
        }
    });

    function handleFile(file) {
        if (file.type !== 'text/plain' && !file.name.endsWith('.txt')) {
            fileInfo.textContent = '请上传TXT格式的文件';
            fileInfo.style.color = 'red';
            return;
        }

        const reader = new FileReader();
        
        reader.onload = function(e) {
            const content = e.target.result;
            
            // 将文件内容保存到local storage，其他信息保存到sync storage
            // 先保存到local storage
            chrome.storage.local.set({
                fileContent: content
            }, function() {
                // 再保存到sync storage
                chrome.storage.sync.set({
                    fileName: file.name,
                    currentPosition: 0
                }, function() {
                    fileInfo.textContent = '已加载文件: ' + file.name;
                    fileInfo.style.color = '#4CAF50';
                    
                    // 更新页码显示
                    updatePageDisplay();
                    
                    // 通知当前激活的标签页更新内容
                    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                        if (tabs.length > 0) {
                            chrome.tabs.sendMessage(tabs[0].id, {
                                action: 'updateContent',
                                content: content,
                                fileName: file.name,
                                position: 0
                            }, function(response) {
                                // 忽略消息传递错误
                                if (chrome.runtime.lastError) {
                                    // 静默处理错误
                                }
                            });
                        }
                    });
                });
            });
        };
        
        reader.readAsText(file, 'utf-8');
    }

    // 保存设置变更
    fontSizeSlider.addEventListener('input', function() {
        fontSizeValue.textContent = fontSizeSlider.value + 'px';
        saveSettings();
    });

    lineHeightSlider.addEventListener('input', function() {
        lineHeightValue.textContent = lineHeightSlider.value;
        saveSettings();
    });

    fontColorPicker.addEventListener('input', function() {
        fontColorValue.textContent = fontColorPicker.value;
        saveSettings();
    });

    hotkeyNext.addEventListener('change', saveSettings);
    hotkeyPrev.addEventListener('change', saveSettings);

    // 显示字数变更
    windowLengthSlider.addEventListener('change', function() {
        // 验证输入值是否在有效范围内
        let value = parseInt(windowLengthSlider.value);
        if (isNaN(value) || value < 20) value = 20;
        if (value > 200) value = 200;
        
        windowLengthSlider.value = value;
        windowLengthValue.textContent = value;
        saveSettings();
        
        // 更新页码显示
        updatePageDisplay();
    });

    // 页码跳转
    goToPageBtn.addEventListener('click', function() {
        const pageNumber = parseInt(currentPageInput.value);
        if (!isNaN(pageNumber) && pageNumber >= 1 && (totalPages === 0 || pageNumber <= totalPages)) {
            // 通知当前标签页跳转页码
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                if (tabs.length > 0) {
                    chrome.tabs.sendMessage(tabs[0].id, {
                        action: 'goToPage',
                        pageNumber: pageNumber
                    }, function(response) {
                        if (chrome.runtime.lastError) {
                            // 静默处理错误
                        }
                    });
                }
            });
        }
    });

    // 回车键跳页
    currentPageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            goToPageBtn.click();
        }
    });

    // 更新页码显示
    function updatePageDisplay() {
        chrome.storage.sync.get(['fileName'], function(result) {
            if (result.fileName) {
                // 从local storage获取文件内容以计算页数
                chrome.storage.local.get(['fileContent'], function(localResult) {
                    if (localResult.fileContent) {
                        const content = localResult.fileContent;
                        const windowLength = parseInt(windowLengthSlider.value);
                        totalPages = Math.ceil(content.length / windowLength);
                        
                        // 获取当前页码
                        chrome.storage.sync.get(['currentPosition'], function(posResult) {
                            const currentPosition = posResult.currentPosition || 0;
                            const currentPage = Math.floor(currentPosition / windowLength) + 1;
                            
                            pageDisplay.textContent = `${currentPage}/${totalPages}`;
                            currentPageInput.max = totalPages;
                            currentPageInput.value = currentPage;
                        });
                    } else {
                        pageDisplay.textContent = '0/0';
                        currentPageInput.max = 1;
                        currentPageInput.value = 1;
                    }
                });
            } else {
                pageDisplay.textContent = '0/0';
                currentPageInput.max = 1;
                currentPageInput.value = 1;
            }
        });
    }

    function saveSettings() {
        const settings = {
            fontSize: fontSizeSlider.value,
            lineHeight: lineHeightSlider.value,
            fontColor: fontColorPicker.value,
            hotkeyNext: hotkeyNext.value.trim(),
            hotkeyPrev: hotkeyPrev.value.trim(),
            windowLength: windowLengthSlider.value
        };
        
        chrome.storage.sync.set(settings, function() {
            // 通知当前激活的标签页更新设置
                chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                    if (tabs.length > 0) {
                        chrome.tabs.sendMessage(tabs[0].id, {
                            action: 'updateSettings',
                            settings: settings
                        }, function(response) {
                            // 忽略消息传递错误
                            if (chrome.runtime.lastError) {
                                console.log('无法发送消息到标签页：' + chrome.runtime.lastError.message);
                            }
                        });
                    }
                });
        });
    }

    // 检查当前标签页状态并同步内容
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if (tabs.length > 0) {
            chrome.storage.sync.get(['fileName', 'currentPosition'], function(result) {
                if (result.fileName) {
                    // 只传递文件名和位置，内容由content.js从local storage加载
                    chrome.tabs.sendMessage(tabs[0].id, {
                        action: 'syncContent',
                        fileName: result.fileName,
                        position: result.currentPosition || 0
                    }, function(response) {
                        // 忽略消息传递错误
                        if (chrome.runtime.lastError) {
                            // 静默处理错误
                        }
                    });
                }
            });
        }
    });
});